#include "threadpool.h"  // 包含你的线程池头文件
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <vector>
#include <thread>

// 服务器端测试
void runServer() {
    // 创建线程池，使用4个工作线程
    ThreadPool pool(4);

    // 创建socket
    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd == -1) {
        std::cerr << "Failed to create socket" << std::endl;
        return;
    }

    // 设置socket选项
    int opt = 1;
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1) {
        std::cerr << "Failed to set socket options" << std::endl;
        close(server_fd);
        return;
    }

    // 绑定地址和端口
    sockaddr_in server_addr{};
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(8888);

    if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
        std::cerr << "Failed to bind socket" << std::endl;
        close(server_fd);
        return;
    }

    // 监听连接
    if (listen(server_fd, 5) == -1) {
        std::cerr << "Failed to listen" << std::endl;
        close(server_fd);
        return;
    }

    std::cout << "Server started, listening on port 8888..." << std::endl;

    // 接受客户端连接
    while (true) {
        sockaddr_in client_addr{};
        socklen_t client_addr_len = sizeof(client_addr);
        int client_fd = accept(server_fd, (struct sockaddr*)&client_addr, &client_addr_len);
        
        if (client_fd == -1) {
            std::cerr << "Failed to accept client connection" << std::endl;
            continue;
        }

        // 将客户端连接添加到线程池处理
        pool.AddTask([client_fd]() {
            char buffer[1024] = {0};
            int valread = read(client_fd, buffer, 1024);
            
            if (valread > 0) {
                std::cout << "Received from client: " << buffer << std::endl;
                // 回显数据给客户端
                send(client_fd, buffer, strlen(buffer), 0);
            }
            
            // 关闭客户端连接
            close(client_fd);
        });
    }

    // 关闭服务器socket
    close(server_fd);
}

// 客户端测试函数
void runClient(const std::string& message) {
    // 创建socket
    int client_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (client_fd == -1) {
        std::cerr << "Failed to create client socket" << std::endl;
        return;
    }

    // 设置服务器地址
    sockaddr_in server_addr{};
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8888);

    // 将IPv4地址从文本转换为二进制形式
    if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0) {
        std::cerr << "Invalid address/ Address not supported" << std::endl;
        close(client_fd);
        return;
    }

    // 连接服务器
    if (connect(client_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
        std::cerr << "Connection Failed" << std::endl;
        close(client_fd);
        return;
    }

    // 发送数据
    send(client_fd, message.c_str(), message.length(), 0);
    std::cout << "Client sent: " << message << std::endl;

    // 接收响应
    char buffer[1024] = {0};
    int valread = read(client_fd, buffer, 1024);
    if (valread > 0) {
        std::cout << "Client received: " << buffer << std::endl;
    }

    // 关闭连接
    close(client_fd);
}

int main() {
    // 在后台启动服务器
    std::thread server_thread(runServer);
    server_thread.detach();

    // 等待服务器启动
    std::this_thread::sleep_for(std::chrono::seconds(1));

    // 创建多个客户端线程并发访问服务器
    std::vector<std::thread> clients;
    for (int i = 0; i < 10; ++i) {
        clients.emplace_back(runClient, "Hello from client " + std::to_string(i));
    }

    // 等待所有客户端完成
    for (auto& client : clients) {
        client.join();
    }

    std::cout << "All clients finished" << std::endl;
    // 注意：实际应用中应该有适当的机制优雅地关闭服务器
    return 0;
}